package com.colbby.datahouse.lock;

import java.util.concurrent.TimeUnit;

public class HashLocalLock<T> implements Lock<T> {

	private LocalLock<T>[] locks = null;
	
	public HashLocalLock(int size) {
		locks = new LocalLock[size];
	}
	
	public HashLocalLock() {
		this(10);
	}
	
	private LocalLock<T> getLock(T t) {
		int hashCode = t.hashCode();
		int index = Math.abs(hashCode) % locks.length;
		if(locks[index] == null) {
			synchronized(this) {
				if(locks[index] == null) {
					locks[index] = new LocalLock<T>();
				}
			}
		}
		return locks[index];
	}
	
	@Override
	public void lock(T t) {
		getLock(t).lock(t);
	}

	@Override
	public void unlock(T t) {
		getLock(t).unlock(t);
	}

	@Override
	public boolean tryLock(T t) {
		return getLock(t).tryLock(t);
	}

	@Override
	public boolean tryLock(T t, long time, TimeUnit timeUnit)
			throws InterruptedException {
		return getLock(t).tryLock(t, time, timeUnit);
	}

}
